//
//  XSquareNewsViewController.swift
//  WeiBoReDo
//
//  Created by 放学跟鸽走 on 2017/4/16.
//  Copyright © 2017年 放学跟鸽走. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 原创cellID
private let originCellId = "originCellId"
/// 转发cellID
private let forwardCellId = "forwardCellId"
class XSquareNewsViewController: XBaseController {
    lazy var newsListViewModel:XSquareNewsListViewModel = XSquareNewsListViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupTable()
        
        // 注册通知
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(browserPhoto),
            name: NSNotification.Name(rawValue: XStatusCellBrowserPhotoNotification),
            object: nil)
        // Do any additional setup after loading the view.
    }
    deinit {
        // 注销通知
        NotificationCenter.default.removeObserver(self)
    }
    /// 浏览照片通知监听方法
    @objc fileprivate func browserPhoto(n: Notification) {
        
        // 1. 从 通知的 userInfo 提取参数
        guard let selectedIndex = n.userInfo?[XStatusCellBrowserPhotoSelectedIndexKey] as? Int,
            let urls = n.userInfo?[XStatusCellBrowserPhotoURLsKey] as? [String],
            let imageViewList = n.userInfo?[XStatusCellBrowserPhotoImageViewsKey] as? [UIImageView]
            else {
                return
        }
        
        // 2. 展现照片浏览控制器
        let vc = HMPhotoBrowserController.photoBrowser(
            withSelectedIndex: selectedIndex,
            urls: urls,
            parentImageViews: imageViewList)
        
        present(vc, animated: true, completion: nil)
    }
    /// 下拉刷新
    override func loadData() {
        tableReFreshCtr.beginRefreshing()
        newsListViewModel.getSquareNews(isPull: false) { (isSuccess) in
            printLog(message: "load more isSuccess \(isSuccess)")
            if isSuccess{
                self.myTableView?.reloadData()
                self.tableReFreshCtr.endRefreshing()
            }
        }
    }
    /// 上拉刷新
    override func loadMore() {
        SVProgressHUD.show(withStatus: "正在加载中")
        newsListViewModel.getSquareNews(isPull: true) { (isSuccess) in
            printLog(message: "load more isSuccess \(isSuccess)")
            if isSuccess{
                //收新列表
                self.myTableView?.reloadData()
                //把上拉刷新的锁打开
                self.isPullUp = false
            }
            SVProgressHUD.dismiss()
        }
    }

   
    
}

// MARK: - UI搭建
extension XSquareNewsViewController{
    func setupTable(){
        
        myTableView?.register(XSquareOriginCell.self, forCellReuseIdentifier: originCellId)
        myTableView?.register(XSquareForwardCell.self, forCellReuseIdentifier: forwardCellId)
        myTableView?.separatorStyle = .none
    }
    
}

// MARK: - tableView数据源及代理
extension XSquareNewsViewController{
    //MARK: TableView DATA SOURCE
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return newsListViewModel.modelList.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let viewModel = newsListViewModel.modelList[indexPath.row]
        //设置对应的cellId
        let isRetweet = (viewModel.squareNews?.forward != nil)
        if isRetweet{
            let cell = tableView.dequeueReusableCell(withIdentifier: forwardCellId, for: indexPath) as? XSquareForwardCell
            cell?.viewModel = viewModel
            cell?.delegate = self
            cell?.indexPath = indexPath
            return cell ?? XSquareForwardCell()
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: originCellId, for: indexPath) as? XSquareOriginCell
            cell?.viewModel = viewModel
            cell?.delegate = self
            cell?.indexPath = indexPath
            return cell ?? XSquareOriginCell()
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return newsListViewModel.modelList[indexPath.row].rowHeight
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
//        let viewModel = newsListViewModel.modelList[indexPath.row]
//        print("select \(viewModel.squareNews?.tpName)")
    }
}


// MARK: - <#XSquareBaseCellDelegate#>
extension XSquareNewsViewController:XSquareBaseCellDelegate{
    func statusCellDidSelectedURLString(urlString: String) {
        let vc = XWebViewController()
        vc.urlString = urlString
        navigationController?.pushViewController(vc, animated: true)
    }
    func statusCellDidSelectedLike(indexPath: IndexPath, model: XSquareNews) {
//        print("\(indexPath.row)---\(model.tpName)")
        newsListViewModel.likeSquare(row: indexPath.row, id: model.id) { (isSuccess) in
            if isSuccess{
                self.myTableView?.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
            }
        }
    }
}
